package com.fs.luban.security.entrypoint;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import com.fs.luban.common.support.JsonResult;
import com.fs.luban.util.RequestUtils;
import com.fs.luban.util.mapper.JsonMapper;

/**
 * @title 鲁班自定义认证出入口
 * @Description 用以解决ajax认证的情况
 * @author fengshi
 */
public class LubanAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Value("${luban.auth.loginUrl}")
	private String LOGIN_URL;
	
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		if (RequestUtils.isAjax(request)) {
			response.setStatus(HttpStatus.OK.value());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			PrintWriter printWriter = response.getWriter();
			printWriter.write(JsonMapper.nonDefaultMapper().toJson(new JsonResult(String.valueOf(HttpStatus.UNAUTHORIZED.value()), authException.getLocalizedMessage())));
			printWriter.flush();
			printWriter.close();
		} else {
			request.setAttribute("authException", authException);
			response.sendRedirect(LOGIN_URL);
		}

	}

}
